import {Component, OnInit, ViewEncapsulation, OnDestroy} from '@angular/core';
import {ActivatedRoute, Params, Router} from "@angular/router";
import {AuthService} from "@shared/service/auth/auth.service";

import {imageUtil, DOWNLOAD_APP_PATH} from "@core/globals/globals.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {PaymentService} from "@payment/payment.service";
import {Observable, Subject} from "rxjs";
import {GoodsOrderRespVO, SNSResult} from "@interface/index";


@Component({
  selector: 'seed-payment-result',
  templateUrl: './payment-result.component.html',
  styleUrls: ['./payment-result.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class PaymentResultComponent implements OnInit, OnDestroy {
  public orderInfo: GoodsOrderRespVO;
  public params = {};
  private userId: string;
  private _alive: boolean;
  public imageUtil = imageUtil.path;
  public downloadAppPath = DOWNLOAD_APP_PATH;
  public ngUnsubscrible: Subject<void> = new Subject<void>();

  constructor(public paymentService: PaymentService,
              public toolsService: ToolsService,
              public route: ActivatedRoute,
              private authService: AuthService,
              private router: Router) {
    this._alive = true;
    this.orderInfo = new GoodsOrderRespVO();
    this.userId = this.authService.getUserId();
  }

  /**
   * @description 获取订单详情 => 如果是支付宝支付的调用此方法
   * @date 20161103
   * @author @chenwh576
   * @param params
   */
  getOrderInfo(params) {
    this.paymentService.getOrderInfo(params)
      .takeUntil(this.ngUnsubscrible)
      .subscribe((res: SNSResult<GoodsOrderRespVO>) => {
        if (res.result === '0') {
          this.orderInfo = res.data;
          this.toolsService.hideLoading();
        }
      });
  }

  /**
   * @description 控制轮训请求订单详情 => 针对微信 () => 10s后取消请求
   * @date 20161103
   * @author @chenwh576
   */
  handleTimeout() {
    return Observable.timer(15000);
  }

  /**
   * @description 间隔1.5s循环请求订单详情 => 针对微信
   * @param param
   */
  whileOrderInfo(param) {
    Observable.interval(1500).takeWhile(() => this._alive)
      .subscribe(() => {
        this.paymentService
          .getOrderInfo(param)
          .takeUntil(this.ngUnsubscrible)
          .subscribe(res => {
            if (!res.data) { return; }

            if ((res.data.status === 1 || res.data.status === 3) && !this.orderInfo) {
               this.orderInfo = res.data;
            }
            if (res.data.status === 2) {
              this.orderInfo = res.data;
              this._alive = false;
              this.toolsService.hideLoading();
              this.ngUnsubscrible.next();
              this.ngUnsubscrible.complete();
            }
          });
      });

  }

  /**
   * 跳转订单详情页
   * @param
   */
  goToOrderDetail() {
    const mchOrderNumber = this.params['mchOrderNumber'];
    this.router.navigate(['/order/detail', mchOrderNumber], {
      queryParams: {orderId: this.params['mchOrderNumber']}
    });
  }

  ngOnInit() {
    this.route.queryParams.subscribe((params: Params) => {
      this.params = params;
      const param = {
        orderNumber: params['mchOrderNumber']
      };
      this.toolsService.showLoading();
      if (!params['orderNumber'] && !params['tradeStatus']) {
        this.handleTimeout()
          .takeUntil(this.ngUnsubscrible)
          .subscribe(() => {
            this._alive = false;
            this.getOrderInfo(param);
          });
        this.whileOrderInfo(param);
      } else {
        this.getOrderInfo(param);
      }
    });
  }

  ngOnDestroy() {
    this._alive = false;
    this.ngUnsubscrible.next();
    this.ngUnsubscrible.complete();
  }


}
